// pages/certif/certif.js

  const app = getApp();
var adds = {};
var picNum;
  Page({
    data: {
      StatusBar: app.globalData.StatusBar,
      CustomBar: app.globalData.CustomBar,
      People: app.globalData.People,
      index: null,
  img_arr: [],
  formdata: '',
      equip: [],  //装备数组
      readyEqu:null,
      colorEN:null,   //用来改颜色的
      dispNo:null, //填到input里面的完整设备号
      equName:null,  //在列表中显示的设备名称 NAME
//输入用数据
      showInputStatus: false,
      inputValue: '',//点击结果项之后替换到文本框的值  上传人的前端文本值
      adapterSource: [],//本地匹配源 大小写要tolowercasea
      bindSource: [],//绑定到页面的数据，根据用户输入动态变化
      personId:null,  //上传人id
},
    upload: function () {
      var that = this;
      var length = this.data.img_arr.length;
      if(length==0){
      wx.request({
        header: {
          "Content-Type": "application/x-www-form-urlencoded"//"application/json"// 
          //"Content-Type": "multipart/form-data; charset=utf-8"
        },
        url: 'http://10.10.11.173:8989/accept/uploadPic ',
        //url: 'http://localhost:9090/course/hidden/uploadPic',
        data: adds,
        method: 'POST',
        success: function (res) {
          console.log('up res ',res);
          
        },
        fail: function (res) {
          console.log("fail", res);
        },
      })
      }
      else 
    if(length!= 0)
    that.upImgs();
    },
    upImgs: function () {  //提交表单时候调用的
      var that = this;
      //if (that.data.img_arr.length != 0)
        for (var i = 0; i < that.data.img_arr.length; i++) {
          adds.picNum = 'pic' + i;  //给表单信息加一个属性用来命名图片
          wx.uploadFile({
            url: 'http://10.10.11.173:8989/accept/uploadPic',
            //url:'http://localhost:9090/course/hidden/uploadPic',
            header: {
              "Content-Type": "application/json"
            },
            filePath: that.data.img_arr[i],
            name: 'file',
            formData: adds,//JSON.stringify(adds),
            success: function (res) {
              console.log("add",adds)
              console.log(res);
              if (res) {
                wx.showToast({
                  title: '已提交发布！',
                  duration: 3000
                });
              }
            },
            fail: function (res) {
              console.log("fail", res);
            },
          })
        }
      that.setData({
        formData: ''
      })
    },

  upimg: function () {  //上传图片
    var that = this;
    let len = 0;
    if (that.data.img_arr != null) { //防止欺骗系统多上传
      len = that.data.img_arr.length;
    };//获取当前已有的图片
    if (this.data.img_arr.length < 1) {
      wx.chooseImage({
        count: 1 - len,
        sizeType: ['original', 'compressed'],
        success: function (res) {
          that.setData({
            img_arr: that.data.img_arr.concat(res.tempFilePaths)
          })
        }
      })
    } else {
      wx.showToast({
        title: '最多上传一张图片',
        icon: 'loading',
        duration: 3000
      });
    }
  },
  clear: function (event) { //取消上传
    console.log(event)
    const nowIndex = event.currentTarget.dataset.id;
    let img_arr = this.data.img_arr;
    img_arr.splice(nowIndex, 1);
    this.setData({
      img_arr
    })
  },
  preview(event) {  //预览图片
    const nowIndex = event.currentTarget.dataset.id;
    const img_arr = this.data.img_arr;
    wx.previewImage({
      current: img_arr[nowIndex],  //当前预览的图片
      urls: img_arr,  //所有要预览的图片
    })
  },


    formSubmit: function (e) {
      console.log('form发生了submit事件，携带数据为：', e.detail.value);
//不选设备不能提交
      if (this.data.readyEqu == '' || !this.data.readyEqu||this.data.personId==null||this.data.img_arr.length==0)
        wx.showToast({
          title: '请填写所有信息',
          icon: 'loading',
          duration: 3000
        });
      else {
          var id = e.target.id;
      //let arr = new Array();
          console.log('e ',e)
          console.log('e v ' , e.detail.value)
          console.log('input ' , e.detail.value.equipId); //表单input的输出信息
          e.detail.value.equipId=this.data.readyEqu; //要上传的是找到的ID
          console.log('input ' , e.detail.value.equipId); //真正要上传的ID值
          console.log('person',this.data.personId)
          e.detail.value.uploadPerson=this.data.personId;
          adds = e.detail.value;
          console.log('adds ', adds);
          this.setData({ formdata: adds });
         // this.upload();
        console.log('验证用户');
        this.checkLog();  //验证加上传
        console.log("log", this.data.logState) 
      }
    },
    checkLog: function () {
      let that = this;
      wx.checkSession({
        success: function (res) {
          console.log(res, '登录未过期')
          that.data.logState = 1;
          console.log("suclog", that.data.logState);
          if (that.data.logState == 1) {    //处于登录状态下则上传
            console.log("log", that.data.logState)
            console.log("user",app.globalData.userInfo);
            that.upload();
          }
        },
        fail: function (res) {
          console.log(res, '登录过期了')
          wx.showToast({  //Modal
            title: '你的登录信息过期了，请重新登录',
            icon: 'loading',
            duration: 1000
          })
          that.data.logState = 0;
          console.log("failog", that.data.logState)
          console.log("no name");
          wx.navigateTo({
            url: '/pages/auth/auth',
          });
        },
      });
    },

  formReset: function (e) {  //清空所有图片
    console.log(e)
    var that = this;
    that.setData(
      { img_arr: [] }, 
      {readyEqu: null},
      { colorEN: null },   //用来改颜色的
      { dispNo: null }
    );
    console.log("reset", this.data.readyEqu, this.data.colorEN, this.data.dispNo);
  },

  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value
    })
  },

  search:function(e){   //input绑定事件，凡是动了控件的表格都要做变化
    var that=this;
    let key = e.detail.value.toLowerCase();
    console.log(key);
    wx.request({
      url: 'http://10.10.11.173:8989/getEquipById',
      //url:'http://localhost:9090/course/getEquipById',
      header: {
        "Content-Type": "application/json"
      },
      method:'get',
      data:{ID:key},
      success: function (res) {
        that.setData({ equip: [] });
        console.log('search res',res);
       // console.log(res.data);
        console.log('search succ equip',that.data.equip);
        let list = that.data.equip;//new Array();
        console.log('list',list)

        if (res.data.length>0) {    //找得到东西就输出
          for (var i = 0; i < res.data.length; i++) {
            list.push(res.data[i]);            
            that.setData({ equip:list});         
            console.log('equip ', that.data.equip[i].ID, that.data.equip[i].EQUIP_NUMBER, that.data.equip[i].EQUIP_TYPE, that.data.equip[i].EQUIP_NAME);
          }  
        }
        else that.setData({ equip: []}); //找不到东西就要设置什么都没有
        //that.data.equip = [];
        console.log('out for ', that.data.equip)  
      },
      fail: function (res) {
        console.log("fail", res);
      },
    })
  },

  eqValue:function(e) {  //点击单元格，原先是index作为value，现在改成对象的ID，同时改颜色
      var that=this;
      
      console.log('tap e ',e);
      console.log('点击单元格，携带value下标值为：', e.currentTarget.id); //点击事件源的id属性值（数组下标）
      var id = e.currentTarget.id;
      console.log('equip.', id + '  ', that.data.equip[id])
      let equ = that.data.equip[id].ID; //数组下标对应的ID属性
      that.setData({ readyEqu: equ });  //实际要上传的文本的值是对象对象ID
      console.log('readyequ ', this.data.readyEqu);
      //改颜色
      this.setData({
        colorEN: that.data.equip[id].ID
        /*colorEN:that.data.equip[id].EQUIP_NUMBER, 
        colorET:that.data.equip[id].EQUIP_TYPE */ //更新 面向属性编程先留着
      })
      //console.log('cl', that.data.equip[id].EQUIP_NUMBER)
      console.log('color '+this.data.colorEN);
    let num = that.data.equip[id].EQUIP_NUMBER;
    this.setData({ dispNo:num});
    console.log('num' + this.data.dispNo);
    },


    bindKeyInput: function (e) {  //input 搜索
    console.log("keyInput",e)
      var currentInputStatu = e.currentTarget.dataset.statu;
      var prefix = e.detail.value//用户实时输入值
      var newSource = []//匹配的结果
      var newId=[] //匹配ID
      console.log("input",currentInputStatu,prefix,newSource);
      if (prefix != "") {
        this.setData(
          {
            showBtnStatus1: false,
            showBtnStatus2: true
          }
        );
        console.log("bstat", this.data.showBtnStatus1, this.data.showBtnStatus2);

        this.data.adapterSource.forEach(function (e) {  //adapterSource放对象的时候取名字出来显示
          console.log(e.NAME)
          console.log("eindex", e.NAME.indexOf(prefix));
          if (e.NAME.indexOf(prefix) != -1) {//返回某个指定的字符串值在字符串中首次出现的位置,如果要检索的字符串值没有出现，则该方法返回 -1
            newSource.push({id:e.ID,name:e.NAME});
          }          
        })
        console.log("newS", newSource)
        this.data.bindSource=newSource
        console.log("test", this.data.bindSource)
      } else {    //prefix ==''
        currentInputStatu = "close";
        this.setData(
          {
            isScroll: true,
            showBtnStatus1: true,
            showBtnStatus2: false
          }
        );
      }
      if (newSource.length != 0) {
        
        this.setData({
          bindSource: newSource
        })
        console.log("bindSource",this.data.bindSource);
        console.log("items", this.data.bindSource.length);
      } else {
        this.setData({
          bindSource: []
        })
        currentInputStatu = "close";
        this.setData(
          {
            isScroll: "{{false}}"
          }
        );
      }
      //关闭 
      if (currentInputStatu == "close") {
        this.setData(
          {
            showInputStatus: false,
            isScroll: true
          }
        );
      }
      // 显示 
      if (currentInputStatu == "open") {
        this.setData(
          {
            showInputStatus: true,
            isScroll: "{{false}}"
          }
        );
      }
    },

    itemtap: function (e) {   //下拉item点击
      var currentInputStatu = e.currentTarget.dataset.statu;
      console.log("tap",e)
      this.setData({
        inputValue: e.target.dataset.name,//e.target.id,
        bindSource: [],
        personId: e.target.id
      })
      //关闭 
      if (currentInputStatu == "close") {
        this.setData(
          {
            showInputStatus: false,
            isScroll: true
          }
        );
      }
      // 显示 
      if (currentInputStatu == "open") {
        this.setData(
          {
            showInputStatus: true,
            isScroll: "{{false}}"
          }
        );
      }
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {    
    let that = this;
    let _custom = wx.getMenuButtonBoundingClientRect()
    console.log("gb", this.data.CustomBar, this.data.StatusBar)
    setTimeout(() => {
      if (that.data.CustomBar === 'undefined' || typeof (that.data.CustomBar === 'undefined')) {
        let new_custom = _custom
        that.setData({
          CustomBar: new_custom.bottom + new_custom.top - that.data.StatusBar
        })
      }
    }, 800);
    console.log("pp", that.data.People, this.data.adapterSource)
    this.data.People = app.globalData.People;
    let names = []
    this.data.People.forEach(function (value) {
      names.push(value.NAME);
    });
    console.log(names);      
    this.data.adapterSource = this.data.People;// names;
    console.log("pp", that.data.People, this.data.adapterSource)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})